from rest_framework.mixins import UpdateModelMixin, CreateModelMixin, RetrieveModelMixin, ListModelMixin, \
    DestroyModelMixin
from rest_framework.response import Response
from rest_framework import serializers
from rest_framework.pagination import PageNumberPagination

from rest_framework.viewsets import GenericViewSet
from apps.minapp.models import Window, Photo_Window
from django_filters.rest_framework import DjangoFilterBackend, FilterSet, CharFilter
from rest_framework.filters import OrderingFilter, SearchFilter

class PhotosSerializers(serializers.ModelSerializer):
    photos = serializers.SerializerMethodField()

    class Meta:
        model = Window
        fields = ['photos']
        # fields = "__all__"
        depth = 1

    def get_photos(self, obj):
        photoList = []
        for photo in obj.photos.all():
            photoList.append(photo.src)
        return photoList


class ShopSerializers(serializers.ModelSerializer):
    photos = serializers.SerializerMethodField()
    class Meta:
        model = Window
        fields = "__all__"
        depth = 1

    def get_photos(self, obj):
        photoList = []
        for photo in obj.photos.all():
            photoList.append(photo.src)
        return photoList


class ShopPagination(PageNumberPagination):
    page_size = 4
    page_query_param = 'page'
    page_size_query_param = 'size'
    max_page_size = 20


class ShopTypeFilter(FilterSet):
    type = CharFilter(field_name='type', lookup_expr='contains')

    class Meta:
        model = Window
        fields = ['type']


class ShopManage(ListModelMixin, RetrieveModelMixin, CreateModelMixin, UpdateModelMixin,
                 DestroyModelMixin, GenericViewSet):
    authentication_classes = []
    queryset = Window.objects.all().filter(disabled=False)
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    search_fields = ['title']
    ordering_fields = ['id', 'rate', 'sales']
    ordering = ['id']
    filterset_class = ShopTypeFilter
    serializer_class = ShopSerializers
    pagination_class = ShopPagination

    def create(self, request, *args, **kwargs):
        newWindow_data = request.data
        photos = newWindow_data["photos"]
        del newWindow_data['photos']
        del newWindow_data['id']
        newWindow = Window.objects.create(**newWindow_data)
        newWindow.save()
        for photo in photos:
            newPhoto = Photo_Window.objects.create(owner=newWindow, src=str(photo['src']))
            newPhoto.save()
        return Response({"error_num": 0})

    def update(self, request, *args, **kwargs):
        shop_id = kwargs['pk']
        shop_data = request.data
        photos = list(shop_data['photos'])
        del shop_data['photos']
        try:
            shop = Window.objects.get(id=shop_id)
            orginPhotos = list((PhotosSerializers(instance=shop).data)['photos'])
            delPhotos = list(set(orginPhotos) - set(photos))
            if len(delPhotos) != 0:
                for photo in delPhotos:
                    delPhoto = Photo_Window.objects.get(src=photo)
                    delPhoto.delete()
            addPhotos = list(set(photos) - set(orginPhotos))
            if len(addPhotos) != 0:
                for photo in addPhotos:
                    Photo_Window.objects.create(owner=shop, src=photo)
            shop.__dict__.update(**shop_data)
            shop.save()
        except Exception as e:
            print(e)
        return Response({'error_num': 0})

    def delete(self, request, *args, **kwargs):
        shop_id = kwargs['pk']
        try:
            shop = Window.objects.get(id=shop_id)
            shop.disabled = True
            shop.save()
        except Exception as e:
            print(e)
        return Response({'error_num': 0})
